<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>每日一面--Redis | Celts</title><meta name="author" content="PaulGeorge"><meta name="copyright" content="PaulGeorge"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="每天一篇面试小知识  本篇着重介绍一下 Redis   写在前面 为什么不直接访问数据库？要在中间加一个Redis缓存？其实我在了解redis之前一直有这样一个疑问，但是既然使用redis作为中间缓存一定是有道理的！ 那么一起来看一下使用redis有哪些好处吧~">
<meta property="og:type" content="article">
<meta property="og:title" content="每日一面--Redis">
<meta property="og:url" content="https://curry3035.gitee.io/posts/3169/index.html">
<meta property="og:site_name" content="Celts">
<meta property="og:description" content="每天一篇面试小知识  本篇着重介绍一下 Redis   写在前面 为什么不直接访问数据库？要在中间加一个Redis缓存？其实我在了解redis之前一直有这样一个疑问，但是既然使用redis作为中间缓存一定是有道理的！ 那么一起来看一下使用redis有哪些好处吧~">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://curry3035.gitee.io/img/avatar.jpg">
<meta property="article:published_time" content="2021-07-15T13:58:58.000Z">
<meta property="article:modified_time" content="2023-04-08T08:56:09.810Z">
<meta property="article:author" content="PaulGeorge">
<meta property="article:tag" content="redis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://curry3035.gitee.io/img/avatar.jpg"><link rel="shortcut icon" href="/img/ic.ico"><link rel="canonical" href="https://curry3035.gitee.io/posts/3169/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":false,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: PaulGeorge","link":"链接: ","source":"来源: Celts","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '每日一面--Redis',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-04-08 16:56:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/background.css"><link rel="stylesheet" href="/css/my.css"><meta name="generator" content="Hexo 5.4.2"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Celts"><span class="site-name">Celts</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">每日一面--Redis</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-07-15T13:58:58.000Z" title="发表于 2021-07-15 21:58:58">2021-07-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-04-08T08:56:09.810Z" title="更新于 2023-04-08 16:56:09">2023-04-08</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E9%9D%A2%E8%AF%95%E7%AF%87/">面试篇</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>8分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="每日一面--Redis"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>每天一篇面试小知识</p>
</blockquote>
<p><strong>本篇着重介绍一下 Redis</strong></p>
<hr>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-16_21-42-34.png"></p>
<p><strong>写在前面</strong></p>
<h4 id="为什么不直接访问数据库？要在中间加一个Redis缓存？"><a href="#为什么不直接访问数据库？要在中间加一个Redis缓存？" class="headerlink" title="为什么不直接访问数据库？要在中间加一个Redis缓存？"></a><font color=#008000>为什么不直接访问数据库？要在中间加一个Redis缓存？</font></h4><p>其实我在了解redis之前一直有这样一个疑问，但是既然使用redis作为中间缓存一定是有道理的！</p>
<p>那么一起来看一下使用redis有哪些好处吧~</p>
<span id="more"></span>



<p><strong>原因：</strong></p>
<ol>
<li>Redis 可以用几十 G 内存来做缓存；</li>
<li>Redis 的缓存可以持久化 （RBD &amp; AOF）；</li>
<li>Redis 可以实现分布式的缓存；</li>
<li>Redis 可以处理每秒百万级的并发，是专业的缓存服务；</li>
<li>Redis 缓存有过期机制；</li>
<li>Redis 有丰富的 API。</li>
</ol>
<p>其中redis最典型的应用场景，当做缓存使用。</p>
<p>因为传统的关系型数据库如Mysql已经不能适用所有的场景了，比如秒杀的库存扣减，APP首页的访问流量高峰等等……</p>
<ul>
<li>服务在处理请求时先从redis里获取结果，获取到了就可以直接返回，没有获取到的话再从数据库里获取，然后存到redis里以供下次使用。</li>
<li>用redis的好处是可以做到分布式，有状态的数据都存在redis里，使业务服务层无状态，以便业务层有很高的可扩展性。</li>
</ul>
<h4 id="先来说下redis是什么吧？"><a href="#先来说下redis是什么吧？" class="headerlink" title="先来说下redis是什么吧？"></a><font color=#008000>先来说下redis是什么吧？</font></h4><p>我：Redis是C语言开发的一个开源的高性能键值对（key-value）的内存数据库；</p>
<p>它是一种NoSQL（非关系型数据库）的数据库。</p>
<p>可以用作数据库、缓存、消息中间件等。</p>
<p>我接着说：Redis作为一个内存数据库。</p>
<ol>
<li>性能优秀，数据在内存中，读写速度非常快，支持并发10W QPS；</li>
<li>单进程单线程，是线程安全的，采用IO多路复用机制；</li>
<li>丰富的数据类型；</li>
<li>支持数据持久化。可以将内存中数据保存在磁盘中，重启时加载；</li>
<li>主从复制，哨兵，高可用；</li>
<li>可以用作分布式锁；</li>
<li>可以作为消息中间件使用，支持发布订阅。</li>
</ol>
<br/>

<h4 id="具体说一下Redis有哪些数据结构呀？"><a href="#具体说一下Redis有哪些数据结构呀？" class="headerlink" title="具体说一下Redis有哪些数据结构呀？"></a><font color=#008000>具体说一下Redis有哪些数据结构呀？</font></h4><p>答：字符串（String）、字典（Hash）、列表（List）、集合（Set）、有序集合（SortedSet）</p>
<p><font color=#FF8C00>后面了解到还有：HyperLogLog、Geo、Pub/Sub 【这是加分的内容】</font></p>
<br/>

<h4 id="使用过Redis分布式锁么，它是怎么回事？"><a href="#使用过Redis分布式锁么，它是怎么回事？" class="headerlink" title="使用过Redis分布式锁么，它是怎么回事？"></a><font color=#008000>使用过Redis分布式锁么，它是怎么回事？</font></h4><p>答：先拿setnx来争抢锁，抢到之后，再用expire给锁加一个过期时间防止锁忘记了释放。</p>
<br/>

<h4 id="假如Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来？"><a href="#假如Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来？" class="headerlink" title="假如Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来？"></a><font color=#008000>假如Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来？</font></h4><p>（这道题很经典啊，网上见过~）</p>
<p>答：使用<code>keys</code>指令可以扫出指定模式的key列表 【 key  keys xxx*】</p>
<br/>

<h4 id="那如果这个redis正在给线上的业务提供服务，那使用keys指令会有什么问题？"><a href="#那如果这个redis正在给线上的业务提供服务，那使用keys指令会有什么问题？" class="headerlink" title="那如果这个redis正在给线上的业务提供服务，那使用keys指令会有什么问题？"></a><font color=#008000>那如果这个redis正在给线上的业务提供服务，那使用keys指令会有什么问题？</font></h4><p>答：redis的单线程的。keys指令会导致线程阻塞一段时间，线上服务会停顿，直到指令执行完毕，服务才能恢复。</p>
<p><font color=#FF8C00>后面了解到：这个时候可以使用scan指令，scan指令可以无阻塞的提取出指定模式的key列表，但是会有一定的重复概率，在客户端做一次去重就可以了，但是整体所花费的时间会比直接用keys指令长。</font></p>
<br/>

<h4 id="使用过Redis做异步队列么，你是怎么用的？"><a href="#使用过Redis做异步队列么，你是怎么用的？" class="headerlink" title="使用过Redis做异步队列么，你是怎么用的？"></a><font color=#008000>使用过Redis做异步队列么，你是怎么用的？</font></h4><p>答：一般使用list结构作为队列，<code>rpush</code>生产消息，<code>lpop</code>消费消息。list还有个指令叫<code>blpop</code>，在没有消息的时候，它会阻塞住直到消息到来。</p>
<br/>

<h4 id="能不能生产一次消费多次呢？"><a href="#能不能生产一次消费多次呢？" class="headerlink" title="能不能生产一次消费多次呢？"></a><font color=#008000>能不能生产一次消费多次呢？</font></h4><p>答：使用pub/sub主题订阅者模式，可以实现 1:N 的消息队列。</p>
<br/>

<h4 id="pub-su-b有什么缺点？"><a href="#pub-su-b有什么缺点？" class="headerlink" title="pub/su b有什么缺点？"></a><font color=#008000>pub/su b有什么缺点？</font></h4><p>在消费者下线的情况下，生产的消息会丢失，得使用专业的消息队列如<code>RabbitMQ</code>等。</p>
<br/>

<h4 id="Redis是怎么持久化的？"><a href="#Redis是怎么持久化的？" class="headerlink" title="Redis是怎么持久化的？"></a><font color=#008000>Redis是怎么持久化的？</font></h4><p>（送分题~）</p>
<p>答：RBD 和 AOF </p>
<ul>
<li><p>RDB做镜像全量持久化，即将整个Redis内存数据持久化到一个文件。</p>
</li>
<li><p>AOF做增量持久化，AOF会将redis中每一步对数据修改的操作记录（日志）append到相应的文件中。</p>
</li>
</ul>
<br/>

<h4 id="那说一下-RBD-和-AOF-的优劣，及其原理吧"><a href="#那说一下-RBD-和-AOF-的优劣，及其原理吧" class="headerlink" title="那说一下 RBD 和 AOF 的优劣，及其原理吧"></a><font color=#008000>那说一下 RBD 和 AOF 的优劣，及其原理吧</font></h4><p>答：</p>
<p><strong>RDB</strong></p>
<p>优点：</p>
<ul>
<li>二进制压缩文件，恢复速度快</li>
</ul>
<p>缺点：</p>
<ul>
<li>可能丢失数据（服务器宕机的时候）</li>
</ul>
<p>原理：</p>
<p><strong>fork</strong> 和 <strong>cow</strong></p>
<ul>
<li>fork是指redis通过创建子进程来进行RDB操作；</li>
<li>cow指的是copy on write，子进程创建后，父子进程共享数据段，父进程继续提供读写服务，写脏的页面数据会逐渐和子进程分离开来。</li>
</ul>
<p><strong>AOF</strong></p>
<p>优点：</p>
<ul>
<li>不易丢失数据，数据完整性好</li>
</ul>
<p>缺点：</p>
<ul>
<li>每一步操作都记录，相对影响性能</li>
<li>数据恢复慢，文件较大</li>
</ul>
<p>原理：</p>
<p>为了降低 IO 消耗，AOF 写文件时，会先将数据写到缓冲区，然后再把缓冲区的内容 flush 到磁盘，这个过程叫做 fsync。</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">$ appendfsync always  //每次写操作都flush，影响性能</span><br><span class="line">$ appendfsync everysec  //每秒flush</span><br><span class="line">$ appendfsync no  //消极等待OS刷新(一般30s),可能丢失数据</span><br></pre></td></tr></table></figure>

<p>相比于always的激进和no的消极，everysec在性能和数据完整性上取了一个折中。</p>
<br/>

<h4 id="是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么？"><a href="#是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么？" class="headerlink" title="是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么？"></a><font color=#008000>是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么？</font></h4><p>答：</p>
<ul>
<li><p>Redis Sentinal 着眼于高可用，在 master 宕机时会自动将 slave 提升为 master，继续提供服务。</p>
</li>
<li><p>Redis Cluster 着眼于扩展性，在单个 redis 内存不足时，使用 Cluster 进行分片存储。</p>
</li>
</ul>
<br/>

<h4 id="Redis-会遇到的缓存雪崩，缓存穿透，缓存击穿吧"><a href="#Redis-会遇到的缓存雪崩，缓存穿透，缓存击穿吧" class="headerlink" title="Redis 会遇到的缓存雪崩，缓存穿透，缓存击穿吧"></a><font color=#008000>Redis 会遇到的缓存雪崩，缓存穿透，缓存击穿吧</font></h4><p>先来了解一下缓存雪崩，缓存穿透，缓存击穿是什么意思！</p>
<p>一、缓存雪崩</p>
<p><strong>含义：</strong></p>
<p>缓存雪崩表示在某一时间段，缓存集中失效，导致请求全部走数据库，有可能搞垮数据库，使整个服务瘫痪。</p>
<p>使缓存集中失效的原因：</p>
<ol>
<li><p>redis服务器挂掉了。</p>
</li>
<li><p>对缓存数据设置了相同的过期时间，导致某时间段内缓存集中失效。（√）</p>
</li>
</ol>
<p><strong>解决方案：</strong></p>
<ol>
<li><p>针对原因1，可以实现redis的高可用，Redis Cluster 或者 Redis Sentinel(哨兵) 等方案。</p>
</li>
<li><p>针对原因2，设置缓存过期时间时加上一个随机值，避免缓存在同一时间过期。</p>
</li>
</ol>
<p>举个荔枝：</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment">## 设置过期时间加上一个随机值</span></span><br><span class="line"><span class="variable">$redis</span>-&gt;<span class="built_in">set</span>(<span class="string">&#x27;article_content_1&#x27;</span>, <span class="string">&#x27;文章内容&#x27;</span>, 60 + mt_rand(1, 60));</span><br><span class="line"><span class="variable">$redis</span>-&gt;<span class="built_in">set</span>(<span class="string">&#x27;article_content_2&#x27;</span>, <span class="string">&#x27;文章内容&#x27;</span>, 60 + mt_rand(1, 60));</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>使用双缓存策略，设置两个缓存，原始缓存和备用缓存，原始缓存失效时，访问备用缓存，备用缓存失效时间设置长点。</li>
</ol>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment">## 原始缓存</span></span><br><span class="line"><span class="variable">$redis</span>-&gt;<span class="built_in">set</span>(<span class="string">&#x27;article_content_2&#x27;</span>, <span class="string">&#x27;文章内容&#x27;</span>, 60);</span><br><span class="line"><span class="comment">## 设置备用缓存，失效时间设置长点</span></span><br><span class="line"><span class="variable">$redis</span>-&gt;<span class="built_in">set</span>(<span class="string">&#x27;article_content_backup_2&#x27;</span>, <span class="string">&#x27;文章内容&#x27;</span>, 1800);</span><br></pre></td></tr></table></figure>



<p>二、缓存穿透</p>
<p><strong>含义：</strong></p>
<p>缓存穿透表示查询一个一定不存在的数据，由于没有获取到缓存，所以没写入缓存，导致这个不存在的数据每次都需要去数据库查询，失去了缓存的意义。</p>
<p>请求的数据大量的没有获取到缓存，导致走数据库，有可能搞垮数据库，使整个服务瘫痪。</p>
<p>比如文章表，一般我们的主键ID都是无符号的自增类型，有些人想要搞垮你的数据库，每次请求都用负数ID，而ID为负数的记录在数据库根本就没有。</p>
<p><strong>解决方案：</strong></p>
<ol>
<li>对于像ID为负数的非法请求直接过滤掉，采用<a href="https://curry3035.gitee.io/posts/11389/"><font color=#FF8C00>布隆过滤器 ( Bloom Filter )</font> </a>。</li>
<li>禁用IP 限制IP访问。</li>
<li> <strong>限流</strong> 每秒最多访问3次。</li>
<li>针对在数据库中找不到记录的，我们仍然将该空数据存入缓存中，当然一般会设置一个较短的过期时间。</li>
</ol>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">//设置文章ID为-10000的缓存为空</span><br><span class="line"><span class="variable">$id</span> = -10000;</span><br><span class="line"><span class="variable">$redis</span>-&gt;<span class="built_in">set</span>(<span class="string">&#x27;article_content_&#x27;</span> . <span class="variable">$id</span>, <span class="string">&#x27;&#x27;</span>, 60);</span><br><span class="line"> </span><br><span class="line">var_dump(<span class="variable">$redis</span>-&gt;get(<span class="string">&#x27;article_content_&#x27;</span> . <span class="variable">$id</span>));</span><br></pre></td></tr></table></figure>



<p>三、缓存击穿</p>
<p><strong>含义：</strong></p>
<p>缓存击穿表示某个key的缓存非常热门，有很高的并发一直在访问，如果该缓存失效，那同时会走数据库，压垮数据库。</p>
<p>缓存击穿与缓存雪崩的区别是这里针对的是某一热门 key 缓存，而雪崩针对的是大量缓存的集中失效。</p>
<p><strong>解决方案：</strong></p>
<ol>
<li>让该热门 key 的缓存永不过期。</li>
<li>使用互斥锁，通过 redis 的 setnx 实现互斥锁。</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">getRedis</span>(<span class="params"></span>)</span><br><span class="line">&#123;</span><br><span class="line">    $redis = <span class="keyword">new</span> <span class="title class_">Redis</span>();</span><br><span class="line">    $redis-&gt;<span class="title function_">connect</span>(<span class="string">&#x27;127.0.0.1&#x27;</span>, <span class="number">6379</span>, <span class="number">60</span>);</span><br><span class="line">    <span class="keyword">return</span> $redis;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//加锁</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">lock</span>(<span class="params">$key, $random</span>)</span><br><span class="line">&#123;</span><br><span class="line">    $redis = <span class="title function_">getRedis</span>();</span><br><span class="line">    <span class="comment">//设置锁的超时时间，避免释放锁失败，del()操作失败，产生死锁。</span></span><br><span class="line">    $ret = $redis-&gt;<span class="title function_">set</span>($key, $random, [<span class="string">&#x27;nx&#x27;</span>, <span class="string">&#x27;ex&#x27;</span> =&gt; <span class="number">3</span> * <span class="number">60</span>]);</span><br><span class="line">    <span class="keyword">return</span> $ret;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//解锁</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">unLock</span>(<span class="params">$key, $random</span>)</span><br><span class="line">&#123;</span><br><span class="line">    $redis = <span class="title function_">getRedis</span>();</span><br><span class="line">    <span class="comment">//这里的随机数作用是，防止更新缓存操作时间过长，超过了锁的有效时间，导致其他请求拿到了锁。</span></span><br><span class="line">    <span class="comment">//但上一个请求更新缓存完毕后，如果不加判断直接删除锁，就会误删其他请求创建的锁。</span></span><br><span class="line">    <span class="keyword">if</span> ($redis-&gt;<span class="title function_">get</span>($key) == $random) &#123;</span><br><span class="line">        $redis-&gt;<span class="title function_">del</span>($key);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//从缓存中获取文章数据</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">getArticleInCache</span>(<span class="params">$id</span>)</span><br><span class="line">&#123;</span><br><span class="line">    $redis = <span class="title function_">getRedis</span>();</span><br><span class="line">    $key = <span class="string">&#x27;article_content_&#x27;</span> . $id;</span><br><span class="line">    $ret = $redis-&gt;<span class="title function_">get</span>($key);</span><br><span class="line">    <span class="keyword">if</span> ($ret === <span class="literal">false</span>) &#123;</span><br><span class="line">        <span class="comment">//生成锁的key</span></span><br><span class="line">        $lockKey = $key . <span class="string">&#x27;_lock&#x27;</span>;</span><br><span class="line">        <span class="comment">//生成随机数，用于设置锁的值，后面释放锁时会用到</span></span><br><span class="line">        $random = <span class="title function_">mt_rand</span>();</span><br><span class="line">        <span class="comment">//拿到互斥锁</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="title function_">lock</span>($lockKey, $random)) &#123;</span><br><span class="line">            <span class="comment">//这里是伪代码，表示从数据库中获取文章数据</span></span><br><span class="line">            $value = $db-&gt;<span class="title function_">getArticle</span>($id);</span><br><span class="line">            <span class="comment">//更新缓存，过期时间可以根据情况自已调整</span></span><br><span class="line">            $redis-&gt;<span class="title function_">set</span>($key, $value, <span class="number">2</span> * <span class="number">60</span>);</span><br><span class="line">            <span class="comment">//释放锁</span></span><br><span class="line">            <span class="title function_">unLock</span>($lockKey, $random);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//等待200毫秒，然后重新获取缓存值，让其他获取到锁的进程取得数据并设置缓存</span></span><br><span class="line">            <span class="title function_">usleep</span>(<span class="number">200</span>);</span><br><span class="line">            <span class="title function_">getArticleInCache</span>($id);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> $ret;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io">PaulGeorge</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io/posts/3169/">https://curry3035.gitee.io/posts/3169/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://curry3035.gitee.io" target="_blank">Celts</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/redis/">redis</a></div><div class="post_share"><div class="social-share" data-image="/img/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/11389/" title="每日一面--布隆过滤器"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">每日一面--布隆过滤器</div></div></a></div><div class="next-post pull-right"><a href="/posts/33770/" title="日积月累"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">日积月累</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/32436/" title="学习--Redis事务、锁机制"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-09</div><div class="title">学习--Redis事务、锁机制</div></div></a></div><div><a href="/posts/26019/" title="实践一下--Redis集群"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-08</div><div class="title">实践一下--Redis集群</div></div></a></div><div><a href="/posts/60188/" title="每日一面--Redis和MySQL数据一致性问题"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-07-22</div><div class="title">每日一面--Redis和MySQL数据一致性问题</div></div></a></div><div><a href="/posts/48441/" title="每日一面--Redis 五种数据结构详解"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-07-21</div><div class="title">每日一面--Redis 五种数据结构详解</div></div></a></div><div><a href="/posts/11389/" title="每日一面--布隆过滤器"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-07-16</div><div class="title">每日一面--布隆过滤器</div></div></a></div><div><a href="/posts/18405/" title="Redis--基本语句"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-05-21</div><div class="title">Redis--基本语句</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">PaulGeorge</div><div class="author-info__description">很多事情就像是旅行一样，当你决定要出发的时候，最困难的那部分其实就已经完成了</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/PaulGeorge123"><i class="fab fa-github"></i><span>GitHub URL</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/PaulGeorge123" target="_blank" title="Github"><i class="fab fa-github"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E4%B8%8D%E7%9B%B4%E6%8E%A5%E8%AE%BF%E9%97%AE%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9F%E8%A6%81%E5%9C%A8%E4%B8%AD%E9%97%B4%E5%8A%A0%E4%B8%80%E4%B8%AARedis%E7%BC%93%E5%AD%98%EF%BC%9F"><span class="toc-number">1.</span> <span class="toc-text">为什么不直接访问数据库？要在中间加一个Redis缓存？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%88%E6%9D%A5%E8%AF%B4%E4%B8%8Bredis%E6%98%AF%E4%BB%80%E4%B9%88%E5%90%A7%EF%BC%9F"><span class="toc-number">2.</span> <span class="toc-text">先来说下redis是什么吧？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%B7%E4%BD%93%E8%AF%B4%E4%B8%80%E4%B8%8BRedis%E6%9C%89%E5%93%AA%E4%BA%9B%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%91%80%EF%BC%9F"><span class="toc-number">3.</span> <span class="toc-text">具体说一下Redis有哪些数据结构呀？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E8%BF%87Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E4%B9%88%EF%BC%8C%E5%AE%83%E6%98%AF%E6%80%8E%E4%B9%88%E5%9B%9E%E4%BA%8B%EF%BC%9F"><span class="toc-number">4.</span> <span class="toc-text">使用过Redis分布式锁么，它是怎么回事？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%81%87%E5%A6%82Redis%E9%87%8C%E9%9D%A2%E6%9C%891%E4%BA%BF%E4%B8%AAkey%EF%BC%8C%E5%85%B6%E4%B8%AD%E6%9C%8910w%E4%B8%AAkey%E6%98%AF%E4%BB%A5%E6%9F%90%E4%B8%AA%E5%9B%BA%E5%AE%9A%E7%9A%84%E5%B7%B2%E7%9F%A5%E7%9A%84%E5%89%8D%E7%BC%80%E5%BC%80%E5%A4%B4%E7%9A%84%EF%BC%8C%E5%A6%82%E4%BD%95%E5%B0%86%E5%AE%83%E4%BB%AC%E5%85%A8%E9%83%A8%E6%89%BE%E5%87%BA%E6%9D%A5%EF%BC%9F"><span class="toc-number">5.</span> <span class="toc-text">假如Redis里面有1亿个key，其中有10w个key是以某个固定的已知的前缀开头的，如何将它们全部找出来？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%82%A3%E5%A6%82%E6%9E%9C%E8%BF%99%E4%B8%AAredis%E6%AD%A3%E5%9C%A8%E7%BB%99%E7%BA%BF%E4%B8%8A%E7%9A%84%E4%B8%9A%E5%8A%A1%E6%8F%90%E4%BE%9B%E6%9C%8D%E5%8A%A1%EF%BC%8C%E9%82%A3%E4%BD%BF%E7%94%A8keys%E6%8C%87%E4%BB%A4%E4%BC%9A%E6%9C%89%E4%BB%80%E4%B9%88%E9%97%AE%E9%A2%98%EF%BC%9F"><span class="toc-number">6.</span> <span class="toc-text">那如果这个redis正在给线上的业务提供服务，那使用keys指令会有什么问题？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E8%BF%87Redis%E5%81%9A%E5%BC%82%E6%AD%A5%E9%98%9F%E5%88%97%E4%B9%88%EF%BC%8C%E4%BD%A0%E6%98%AF%E6%80%8E%E4%B9%88%E7%94%A8%E7%9A%84%EF%BC%9F"><span class="toc-number">7.</span> <span class="toc-text">使用过Redis做异步队列么，你是怎么用的？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%83%BD%E4%B8%8D%E8%83%BD%E7%94%9F%E4%BA%A7%E4%B8%80%E6%AC%A1%E6%B6%88%E8%B4%B9%E5%A4%9A%E6%AC%A1%E5%91%A2%EF%BC%9F"><span class="toc-number">8.</span> <span class="toc-text">能不能生产一次消费多次呢？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#pub-su-b%E6%9C%89%E4%BB%80%E4%B9%88%E7%BC%BA%E7%82%B9%EF%BC%9F"><span class="toc-number">9.</span> <span class="toc-text">pub&#x2F;su b有什么缺点？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Redis%E6%98%AF%E6%80%8E%E4%B9%88%E6%8C%81%E4%B9%85%E5%8C%96%E7%9A%84%EF%BC%9F"><span class="toc-number">10.</span> <span class="toc-text">Redis是怎么持久化的？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%82%A3%E8%AF%B4%E4%B8%80%E4%B8%8B-RBD-%E5%92%8C-AOF-%E7%9A%84%E4%BC%98%E5%8A%A3%EF%BC%8C%E5%8F%8A%E5%85%B6%E5%8E%9F%E7%90%86%E5%90%A7"><span class="toc-number">11.</span> <span class="toc-text">那说一下 RBD 和 AOF 的优劣，及其原理吧</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%98%AF%E5%90%A6%E4%BD%BF%E7%94%A8%E8%BF%87Redis%E9%9B%86%E7%BE%A4%EF%BC%8C%E9%9B%86%E7%BE%A4%E7%9A%84%E9%AB%98%E5%8F%AF%E7%94%A8%E6%80%8E%E4%B9%88%E4%BF%9D%E8%AF%81%EF%BC%8C%E9%9B%86%E7%BE%A4%E7%9A%84%E5%8E%9F%E7%90%86%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-number">12.</span> <span class="toc-text">是否使用过Redis集群，集群的高可用怎么保证，集群的原理是什么？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Redis-%E4%BC%9A%E9%81%87%E5%88%B0%E7%9A%84%E7%BC%93%E5%AD%98%E9%9B%AA%E5%B4%A9%EF%BC%8C%E7%BC%93%E5%AD%98%E7%A9%BF%E9%80%8F%EF%BC%8C%E7%BC%93%E5%AD%98%E5%87%BB%E7%A9%BF%E5%90%A7"><span class="toc-number">13.</span> <span class="toc-text">Redis 会遇到的缓存雪崩，缓存穿透，缓存击穿吧</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/47231/" title="POI读取Excel问题">POI读取Excel问题</a><time datetime="2023-04-11T01:00:00.000Z" title="发表于 2023-04-11 09:00:00">2023-04-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/8422/" title="Excel大文件的上传">Excel大文件的上传</a><time datetime="2023-04-10T01:00:00.000Z" title="发表于 2023-04-10 09:00:00">2023-04-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/55119/" title="每日一面--Files工具类">每日一面--Files工具类</a><time datetime="2023-01-01T01:00:00.000Z" title="发表于 2023-01-01 09:00:00">2023-01-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/34600/" title="面试一下--JUC入门">面试一下--JUC入门</a><time datetime="2022-09-10T01:00:00.000Z" title="发表于 2022-09-10 09:00:00">2022-09-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/16284/" title="每日一面--字符流和字节流">每日一面--字符流和字节流</a><time datetime="2022-07-01T01:00:00.000Z" title="发表于 2022-07-01 09:00:00">2022-07-01</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By PaulGeorge</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>